#include <pvm3.h>

#include "job.h"
#include <string.h>


#define MAX_JOB 400

/* Fonction qui renvoi un job a effectue. */

struct job * get_job(unsigned long max)
{
  static int current_job = 1;
  if (current_job == MAX_JOB)
    {
      printf("no more jobs");
      return NULL;
    }
  else
    {
      struct job * new_job = malloc(sizeof(struct job));
      new_job->init = current_job*max/400;
      new_job->end = (current_job+1)*max/400;
      current_job++;
      return new_job;
    }
} 



int master(int nb_slave, char* password, char* size_max)
{
  
  char buf[atoi(size_max)];
  
  int buf_id;
  int tag;
  int slave_id;
  pvm_initsend(PvmDataDefault);  
  int *tids=malloc(nb_slave*sizeof(int));
  char **argv = malloc(3*sizeof(char*));
  argv[0]=password;
  argv[1]=size_max;
  argv[2]=NULL;

  //printf("spawn\n");
  if(pvm_spawn("slave", argv, PvmTaskDefault, "", nb_slave, tids)<nb_slave)
    {
      printf("spawn foireux\n");
    }
  int i;
  ///////
  char* deb = malloc(atoi(size_max)*sizeof(char));
  strcpy(deb,"aaa");
  char* fin = malloc(atoi(size_max)*sizeof(char));
  strcpy(fin,"zzz");
  char* msg = malloc(2*atoi(size_max)*sizeof(char));
  strcpy(msg,deb);
  strcat(msg," ");
  strcat(msg,fin);
  printf("msg: %s\n",msg);
  int nb_actifs=1;
  //printf("deb:%s\n",deb);
  //printf("tids[0]:%d\n",tids[0]);
  // initialisation : on envoie deux string a tous les esclaves
  //for(i=0;i<nb_slave;i++)
  // {
      /*pvm_pkstr(deb);
      pvm_send(tids[i],1);
      pvm_pkstr(fin);
      pvm_send(tids[i],1);
      nb_actifs++;*/
  pvm_pkstr(msg);
  pvm_send(tids[0],1);
  //}
  printf("ok\n");
  // on attend les reponses
  
  buf_id = pvm_recv(-1,-1);
  //printf("coucou \n");
  pvm_upkstr(msg);      
  pvm_bufinfo(buf_id,(int*)NULL,&tag,&slave_id);
  //  printf("received : %s\n",msg);
  if(tag == 2) //si un des esclaves a trouve on arrete tout
    {
      printf("trouvé : %s\n",msg);
      /*for(i=0;i<nb_slave;i++)
	{
	pvm_kill(tids[i]);
	}*/
    }
  else // sinon on renvoie une plage de recherche
    {
      //nb_actifs--;
      printf("pas trouvé\n");
      /*if(il reste une plage)
	{
	on lui renvoie
	}
	else
	{
	nb_actifs--;
	pvm_kill[slave_id];
	}*/ /*
	      printf(".....\n");*/
    }
  
  
  //}
  
  return 0; 
}



int main(int argc,char*argv[])
{
  if(argc < 3){
    printf("expected slave_nbr|password|size_max\n");
    return 0;
  }
  master(atoi(argv[1]),argv[2],argv[3]);
  return EXIT_SUCCESS;
  
}


